<template>
	<view class="page-wrap" :data-theme="theme" :class="theme" :style="globalColor.style">
		<HeadCustom title="语音介绍" :isAppBtn="false"></HeadCustom>
		<view class="content-wrap">
			<view class="examine-tips font24 fboxRow Ycenter" v-if="fromData.auditStatus == 0">审核中：1~2个工作日内反馈，请及时关注</view>
			<view class="examine-tips font24 fboxRow Ycenter" v-if="fromData.auditStatus == 2">语音介绍中含有敏感词汇，请及时修改</view>
			<view class="card bg-base">
				<view class="hd fboxRow Ycenter font32">
					<view class="flex1">设置语音介绍</view>
					<view class="switch" v-if="fromData.auditStatus == 1">
						<u-switch v-model="fromData.isShow" :disabled="fromData.auditStatus != 1" inactiveColor="#E8EDF1" activeColor="#CC9870" :activeValue="1" :inactiveValue="0" @change="offChange"></u-switch>
					</view>
				</view>
				<view class="bd">
					<view v-if="!fromData.resumeUrl" class="not flex1 color-969699 font28">
						<view class="not-item fboxRow Ycenter Xcenter bg-base">
							<view class="fboxCol flex1 Ycenter Xcenter" @click="showVoice(1)">
								<image class="icon" src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.5.0/recruit/voice-1.png" mode="aspectFill"></image>
								<view class="tit mt16 font28 lh40">Ai语音</view>
							</view>
							<!-- #ifdef MP-WEIXIN -->
							<view class="fboxCol flex1 Ycenter Xcenter" @click="showVoice(2)">
								<image class="icon" src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.5.0/recruit/voice-2.png" mode="aspectFill"></image>
								<view class="tit mt16 font28 lh40">我要录制</view>
							</view>
							<!-- #endif -->
							<view class="fboxCol flex1 Ycenter Xcenter" @click="changeAudio">
								<image class="icon" src="https://ebc-prod.cdn.benwunet.com/uni-static/img3.5.0/recruit/voice-3.png" mode="aspectFill"></image>
								<view class="tit mt16 font28 lh40">导入语音</view>
							</view>
						</view>
					</view>
					<view class="fboxCol audio-slider" v-if="fromData.resumeUrl">
						<view class='fboxRow Ycenter audio-item bg-F7F8FF'>
							<view class="icon-btn" @click='_playAudio'>
								<template v-if="showTime1 == '00:00'">
									<text class="bwfont bw-yuyin"></text>
								</template>
								<template v-else>
									<text class="bwfont bw-bofang" v-show='isPlayAudio'></text>
									<text class="bwfont bw-zanting" v-show='!isPlayAudio'></text>
								</template>	
							</view>
							<view class='fboxCol flex1 info'>
								<view class="fboxRow Ycenter font28">语音介绍</view>
								<slider class="slider" style="width:100%;" @change='sliderChange' activeColor='#CC9870'
									block-color="#CC9870" block-size="10" :value='audioSeek' />
								<view class='fboxRow Ycenter font20'>{{showTime1}} <view class="flex1"></view> {{showTime2}}</view>
							</view>
						</view>
						<view class="fboxRow Ycenter audio-state lh40">
							<view class="flex1">
								<text class="font28 state" v-if="fromData.auditStatus != 1">{{fromData.auditStatus==0 ? '待审核': fromData.reason || ''}}</text>
							</view>
							<u-icon @click="del" color="#969699" size="32rpx" name="trash"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 录制语音 -->
		<template v-if="isVoicePopup">
			<AudioRecord :show.sync='isVoicePopup' :fromData.sync="fromData" @update="recordUpdate" />
		</template>
		<!-- AI语音 -->
		<template v-if="isAiPopup">
			<AudioAI :show.sync="isAiPopup" :fromData.sync="fromData" @update="aiUpdate" />
		</template>
	</view>
</template>
<script>
import { strTrim } from '@/static/js/common.js';
import AudioRecord from './vita-audio-record.vue'
import AudioAI from './vita-audio-ai.vue'

import { getCardVoice, cardVoiceUpdate, cardVoiceDel } from '@/api/card.js';

import { resumeAudioDetail, resumeAudioVideoDel, resumeAudioVideoUpdate, resumeAudioVideoShow } from '@/api/recruit.js';
import {fileUploadAnon} from '@/api/index.js'

let innerAudioContext = null
let recorderManager = uni.getRecorderManager();
export default {
	components: {
		AudioRecord,
		AudioAI
	},
	data() {
		return {
			theme: getApp().globalData.appTheme,
			globalColor: getApp().globalData.globalColor,
			fromData: {
				"auditStatus": '',
				// "id": "",
				"isShow": 0,
				"memberId": "",
				"resumeContent": "",
				"resumeType": 0,
				"resumeUrl": "",
				"type": 0
			},
			isAiPopup: false, // ai语音
			isVoicePopup: false, // 录制语音
			// 已经上传的语音播放参数
			audioDuration: '', // 语音总时间
			audioSeek: 0, // 语音进度
			showTime1: "00:00", // 语音时间
			showTime2: "00:00", // 语音时间
			isPlayAudio: false, // 语音是否播放
			isApp: false,
			
		};
	},
	onLoad(option) {
		this.getDetail();
	},
	onUnload() {
		innerAudioContext.destroy()
	},
	mounted() {
		window.appFileCallback = this.appFileCallback;
	},
	methods: {
		// 获取音频信息
		getDetail() {
			resumeAudioDetail().then(res => {
				this.fromData = res.data;
				if(res.data.resumeUrl){
					this.audioSeek = 0
					this.audioDuration = 0
					this.showTime1 = "00:00"
					this.showTime2 =  "00:00"
					this.isPlayAudio = false
					this.Initialization()
				}
			});
		},
		// 语音开关
		offChange() {
			if(this.fromData.id){
				resumeAudioVideoShow({
					"id": this.fromData.id,
					"isShow": this.fromData.resumeType
				}).then(res=>{
					if (res.data) {
						uni.showToast({
							icon: 'none',
							title: '设置成功'
						})
					}
				})
			}else{
				uni.showToast({
					icon: 'none',
					title: '请先上传语音简历'
				})
			}
		},
		// 删除接口
		del() {
			resumeAudioVideoDel({ id: this.fromData.id }).then(res => {
				if (res.data) {
					uni.showToast({
						icon: 'none',
						title: '删除成功'
					})
					this.getDetail()
				}
			})
		},
		// 更新语音简历
		updateDetail(){
			let reqData = {
				"resumeContent": this.fromData.resumeContent,
				"resumeType": 0,
				"resumeUrl": this.fromData.resumeUrl
			}
			if(this.fromData.id){ reqData.id = this.fromData.id }
			resumeAudioVideoUpdate(reqData).then(res=>{
				if (res.data) {
					this.getDetail()
				}
			})
		},
		// 录制语音更新
		recordUpdate(url){
			this.fromData.resumeUrl = url
			this.updateDetail()
		},
		// ai语音更新
		aiUpdate(data){
			console.log(data)
			this.updateDetail()
		},
		// 选择语音文件
		changeAudio() {
			const { bw_link } = getApp().getBWData(['bw_link']);
			if (bw_link.isApp) {
				// app兼容进行交互
				const data = { type: 'fileUpload', action: 'contentVideo' };
				let that = this;
				this.$bridge.callHandler('recruitHandler', data, res => {
					console.log('recruitHandler  ', '返回');
					that.appFileCallback(res);
				});
			} else {
				// #ifdef H5
				//选择音频文件
				uni.chooseFile({
					count: 1, //选取的文件个数限制
					extension: ['.mp3'], //可定义允许哪些后缀的文件可被选择
					success: res => {
						let tempFilePaths = res.tempFiles[0];
						console.log(tempFilePaths);
						const name = tempFilePaths.name || tempFilePaths.path;
						if (name.indexOf('.mp3') == name.length - 4) {
							this.uploadAudio(tempFilePaths);
						} else {
							uni.showToast({
								icon: 'none',
								title: '请选择MP3文件'
							});
						}
					}
				});
				// #endif
				// #ifdef MP-WEIXIN
				// 从微信聊天消息中选择文件
				wx.chooseMessageFile({
					count: 1, //选取的文件个数限制
					type: 'file', //可定义允许哪些后缀的文件可被选择
					extension: ['mp3'],
					success: res => {
						let tempFilePaths = res.tempFiles[0];
						const name = tempFilePaths.name || tempFilePaths.path;
						if (name.indexOf('.mp3') == name.length - 4) {
							this.uploadAudio(tempFilePaths);
						} else {
							uni.showToast({
								icon: 'none',
								title: '请选择MP3文件'
							});
						}
					}
				});
				// #endif
			}
		},
		// 上传音频
		uploadAudio(file) {
			uni.showLoading({
				title: '上传中',
				mask: true
			})
			// 上传音频文件
			fileUploadAnon(file).then(res => {
				if (res.data) {
					this.fromData.resumeUrl = res.data.url
					this.updateDetail()
				}
			}).finally(err=>{
				uni.hideLoading()
			})
		},
		// app上传视频回调
		appFileCallback(res) {
			console.log('res==>', res.fileUrl, res.action);
			if (res.action == 'contentVideo') {
				this.fromData.resumeUrl = res.fileUrl
				this.updateDetail()
			}
		},
		//初始化播放器，获取duration
		Initialization() {
			var t = this;
			if(!innerAudioContext){
				innerAudioContext = uni.createInnerAudioContext();
			}
			if (this.fromData.resumeUrl) {
				//设置src
				innerAudioContext.src = this.fromData.resumeUrl;
				//运行一次
				innerAudioContext.onCanplay(() => {
					//初始化duration
					this.audioDuration = innerAudioContext.duration
					setTimeout(function() {
						//延时获取音频真正的duration
						var duration = innerAudioContext.duration;
						this.audioDuration = duration
						t.audioDuration = duration
					console.log('innerAudioContext.duration', innerAudioContext.duration, t.conversion(duration))
						t.showTime2 = t.conversion(duration)
					}, 500)
				})
				innerAudioContext.onPause(() => {
					if (t.isPlayAudio) {
						this._playAudio()
					}
				})
				innerAudioContext.onTimeUpdate((e)=>{
					this.loadaudio()
				})
				innerAudioContext.onEnded((e)=>{
					this.audioSeek = 0
					this.isPlayAudio= false
					this.showTime1=`00:00`
				})
			}
		},
		//拖动进度条事件
		sliderChange(e) {
			innerAudioContext.src = this.fromData.resumeUrl;
			//获取进度条百分比
			var value = e.detail.value;
			var duration = this.audioDuration;
			//根据进度条百分比及歌曲总时间，计算拖动位置的时间
			value = parseInt(value * duration / 100);
			//更改状态
			this.audioSeek = value
			this.isPlayAudio = true
			//调用seek方法跳转歌曲时间
			innerAudioContext.seek(value);
			//播放歌曲
			innerAudioContext.play();
		},
		// 播放、暂停按钮
		_playAudio() {
			//获取播放状态和当前播放时间
			var isPlayAudio = this.isPlayAudio;
			//更改播放状态
			this.isPlayAudio = !this.isPlayAudio
			if (isPlayAudio) {
				// 如果在播放则记录播放的时间，暂停
				innerAudioContext.pause();
			} else {
				//如果在暂停，获取播放时间并继续播放
				innerAudioContext.play();
			}
		},
		// 更新时间
		loadaudio() {
			const that = this
			const duration = innerAudioContext.duration;
			const currentTime = innerAudioContext.currentTime
			//当进度条完成，停止播放，并重设播放时间和进度条
			if (time >= 100) {
				innerAudioContext.stop();
				that.audioSeek = 0
				that.audioDuration= duration
				that.isPlayAudio= false
				that.showTime1=`00:00`
				return false;
			}
			//播放时间
			var time = currentTime.toFixed(0)
			that.showTime1 = that.conversion(time)
			//计算进度
			that.audioSeek = ((time/duration).toFixed(2))*100
		},
		// 计算时间
		conversion(duration){
		  var min = parseInt(duration / 60);
		  var sec = parseInt(duration % 60);
		  if (min.toString().length == 1) {
			min = `0${min}`;
		  }
		  if (sec.toString().length == 1) {
			sec = `0${sec}`;
		  }
		  return `${min}:${sec}`
		},
		// 显示录制，ai语音弹窗
		showVoice(type){
			if(type == 1){
				// ai语音
				this.isAiPopup = true
			}else if(type == 2){
				// 打开录音弹窗
				// #ifdef H5
				uni.showToast({
					icon: 'none',
					title: '浏览器暂不支持'
				});
				// #endif
				// #ifdef MP-WEIXIN
				 this.isVoicePopup = true
				// #endif
			}
		},
	}
};
</script>

<style lang="scss" scoped>
.content-wrap {padding: 0 40rpx 60rpx;}
.btn-gray{background: #E8EDF1;}
.audio-slider{padding: 36rpx 0 0;}
.audio-slider .audio-item{padding: 16rpx 24rpx; width: 606rpx;height: 132rpx;background: #F4F8FB;border-radius: 10rpx;color: var(--contentFontLightColor)}
.slider{margin: 0;}
.audio-slider .icon-btn{margin-right: 20rpx;}
.audio-slider .icon { width: 38rpx; height: 38rpx; }
.audio-state{margin-top: 18rpx;}
.audio-state .state{color: var(--contentSearchTitleColor);}

.examine-tips {padding: 0 22rpx;width: 670rpx;height: 58rpx;background: #e56d55;border-radius: 4rpx;color: var(--contentBgImageTitleColor);}
.not-item {}
.not-item .icon {width: 96rpx;height: 96rpx;}
.not-item .tit { margin-top: 16rpx;}

.card {
	margin-top: 22rpx;
	padding: 24rpx 32rpx;
	background-color: var(--viewBgColor);
	border-radius: 12rpx;
}

.card .hd {
	height: 44rpx;
}
.card .not {
	padding: 74rpx 0 10rpx;
}

.switch {
	transform: scale(0.8);
	margin-right: -14rpx;
}

</style>
